/**
 * Created by fjlongtou on 2016/11/29.
 */
var mysql = require('mysql');
//删除原有表格数据
function deleteTableData(connection,tableName,callback) {
    //删除所有数据
    var  userDelSql = "DELETE FROM "+tableName;
    var  userDelSql_Params = [];
    connection.query(userDelSql,userDelSql_Params,function (err, result) {
        if(err){
            console.log(tableName+'删除出错-----'+err.message);
            return;
        }
        if(callback)callback(result.affectedRows);
        console.log(tableName+'成功删除'+result.affectedRows+'行');
    });
}
//插入数据
function insertTableData(connection,tableName,index,data,callback) {
    var keys = [];
    var  userAddSql_Params = [];
    for(var key in data)
    {
        keys.push(key);
        userAddSql_Params.push(data[key]);
    }
    //增加
    var userAddSql = 'INSERT INTO '+tableName+'(';
    var tmpvalues = '';
    for(var idx=0; idx<keys.length; idx++)
    {
        userAddSql += keys[idx];
        tmpvalues += '?';
        if (idx < keys.length-1)
        {
            userAddSql += ',';
            tmpvalues += ',';
        }
    }
    userAddSql += ') VALUES('+tmpvalues+')';
    // console.log("执行插入"+userAddSql);
    //增 add
    connection.query(userAddSql,userAddSql_Params,function (err, result) {
        if(err){
            console.log(tableName+'插入数据出错 ',err.message);
            return;
        }
        if(callback)callback(result.affectedRows);
        console.log(tableName+'插入成功第'+index+'行');
    });
}
exports.operateTable = function(config,tableName,datas) {
    var connection = mysql.createConnection(config);
    connection.connect();
    //删除
    //deleteTableData(connection,tableName);
    for (var idx=0; idx<datas.length; idx++)
    {
        insertTableData(connection,tableName,idx,datas[idx]);
    }
    connection.end();
}